<?php

namespace app\index\service;

use app\common\ConfigBase;
use app\common\model\ToolModel;
use app\index\model\ShipModel;
use think\Db;

class ShipService
{
    static public $ybStatus = [
        0 => '未推送'
        , 10 => '已推送'
        , 1 => '预报成功'
        , 2 => '人工判断'
        , 3 => '预报失败'
    ];
    static public $bhStatus = [
        0 => '未推送'
        , 1 => '已推送'
        , 10 => '待打印'
        , 20 => '待打标'
        , 30=> '待装箱'
        , 40=> '已装箱'
        , 50=> '已挂起'
        , 60=> '已取消'
        , 70=> '缺货'
    ];
    //0空1仓库出货2货代收货3出口清关4离港5抵港6进口清关7派送8上架',
    static public $tcStatus = [
        0 => ''
        , 1 => '订舱'
        , 2 => '仓库出货'
        , 3 => '货代收货'
        , 4 => '出口清关'
        , 5 => '离港'
        , 6 => '抵港'
        , 7 => '进口清关'
        , 8 => '派送'
        , 9 => '上架'
        , 20 => '已推送'
    ];
    static public $ybrStatus = [
        0 => '',
        1 => '配送'
    ];

    /**
     *上传发运明细处理
     * @param $data
     * @return array
     * @author xiejunyu
     */
    static public function uploadHandle($data)
    {
        $msg = [];//提示信息
        $sku = [];
        $getShop = ConfigBase::getShopKeyName();
        $getShopNames = array_keys($getShop);
        $res = [];
        $skuShop = [];
        foreach ($data as $k => &$v) {
            $line = $k + 2;
            if (!in_array($v[0], $getShopNames)) {
                $msg[] = "第{$line}行店铺在系统上不存在";
            }
            if (empty($v[1])) {
                $msg[] = "第{$line}行sku不能为空";
            }
            if (in_array($v[1] . $v[0], $skuShop)) {
                $msg[] = "第{$line}行存在重复店铺sku";
            }
            if (!preg_match("/^[1-9][0-9]*$/", $v[2])) {
                $msg[] = "第{$line}行理论需求量必须为正整数";
            }
            if (!empty($v[3])) {
                if (!preg_match("/^[1-9][0-9]*$/", $v[3])) {
                    $msg[] = "第{$line}行实际计划发货量必须为正整数";
                }
            }
            if (!empty($v[4])) {
                if ($v[4] < 0) {
                    $msg[] = "第{$line}行单位体积必须大于0";
                }
                if (!preg_match("/(^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$)|(^[1-9]\d*$)/", $v[4])) {
                    $msg[] = "第{$line}行单位体积{$v[4]}必须为数字";
                }
            }
            $v[1] = strtoupper($v[1]);
            $sku[] = $v[1];
            $skuShop[] = $v[1] . $v[0];
        }
        if (!empty($msg)) {
            return returnArr(500, $msg);
        }
        $skuInfo = \app\common\service\SkuService::getBatchInfoBySku($sku, ['ean', 'cnname', 'enname', 'weighting_price']);
        if (empty($skuInfo)) {
            $msg[] = "SKU信息获取失败!";
        }
        foreach ($data as $k2 => $v2) {
            $temp = [];
            $temp['shop_id'] = $getShop[$v2[0]];
            $temp['shop_str'] = $v2[0];
            $temp['sku'] = $v2[1];
            if (empty($skuInfo[$temp['sku']])) {
                $msg[] = "sku:{$temp['sku']}在基础资料不存在";
                continue;
            }
            $temp['sku_name'] = $skuInfo[$temp['sku']]['cnname'] ?? '';
            $temp['sku_enname'] = $skuInfo[$temp['sku']]['enname'] ?? '';
            $temp['ean'] = $skuInfo[$temp['sku']]['ean'] ?? '';
            $temp['demand_quantity'] = $v2[2];
            $temp['real_quantity'] = $v2[3];
            $temp['unit_volume'] = $v2[4];
            $temp['total_volume'] = $temp['real_quantity'] * $temp['unit_volume'];
            $temp['unit_price'] = $skuInfo[$temp['sku']]['weighting_price'] ?? 0;
            $res[] = $temp;
        }
        if (!empty($msg)) {
            return returnArr(500, $msg);
        }
        return returnArr(1, '', $res);
    }

    static public function uploadSignHandle($data, $param)
    {
        $msg = [];//提示信息
        $sku = [];
        $getShop = ConfigBase::getShopKeyName();
        $getShopNames = array_keys($getShop);
        $res = [];
        $skuShop = [];
        foreach ($data as $k => &$v) {
            $line = $k + 2;
            if (!in_array($v[0], $getShopNames)) {
                $msg[] = "第{$line}行店铺在系统上不存在";
            }
            if (empty($v[1])) {
                $msg[] = "第{$line}行sku不能为空";
            }
            if (in_array($v[1] . $v[0], $skuShop)) {
                $msg[] = "第{$line}行存在重复店铺sku";
            }
            if (!preg_match("/^[1-9][0-9]*$/", $v[2])) {
                $msg[] = "第{$line}行实际计划发货量必须为正整数";
            }
            $v[1] = strtoupper($v[1]);
            $sku[] = $v[1];
            $skuShop[] = $v[1] . $v[0];
        }
        if (!empty($msg)) {
            return returnArr(500, $msg);
        }
        $shopSku = [];
        $list = json_decode($param['list'], true);
        foreach ($list as $k3 => $v3) {
            $shopSku[$v3['shop_id'] . $v3['sku']] = $v3;
        }
        if (!empty($msg)) {
            return returnArr(500, $msg);
        }
        $signData = [];
        foreach ($data as $k2 => $v2) {
            $shop_id = $getShop[$v2[0]];
            $signData[$shop_id . $v2[1]] = [
                "ybr_status" => 1
                , "real_quantity" => $v2[2]
            ];
            if (empty($shopSku[$shop_id . $v2[1]])) {
                $msg[] = "标记的店铺{$v2[0]}sku{$v2[1]}在明细中不存在!";
            }
        }
        if (!empty($msg)) {
            return returnArr(500, $msg);
        }
        foreach ($shopSku as $k4 => $v4) {
            $info = $signData[$k4] ?? $v4;
            $temp = $v4;
            $temp['total_volume'] = $info['real_quantity'] * $v4['unit_volume'];
            $temp['ybr_status'] = $info['ybr_status'] ?? 0;
            $temp['ybr_str_status'] = self::$ybrStatus[$temp['ybr_status']];
            $res[] = $temp;
        }
        return returnArr(1, '', $res);
    }

    static public function edit($param)
    {

    }

    /**
     *创建或编辑发运计划单
     * @param $param
     * @return array
     * @author xiejunyu
     */
    static public function create($param)
    {
        if (empty($param['company_id_out']) || empty($param['warehouse_id_out'])
            || empty($param['warehouse_id_rec']) || empty($param['country_id_rec']) || empty($param['list']) || empty($param['ship_time_early']) || empty($param['ship_time_late'])
            || empty($param['trading_company']) || empty($param['retail_company'])) {
            return returnArr(500, '参数不全');
        }
        if (strtotime($param['ship_time_early']) > strtotime($param['ship_time_late'])) {
            return returnArr(500, '最晚发运时间不能小于最早发运时间');
        }
        $country = ToolModel::findByAttributes('base_country', ['name_zh' => $param['country_id_rec']]);
        $plan = [];
        $plan['company_id_out'] = $param['company_id_out'];
        $plan['warehouse_id_out'] = $param['warehouse_id_out'];
        //$plan['shop_id_rec']=$param['shop_id_rec'];
        $plan['warehouse_id_rec'] = $param['warehouse_id_rec'];
        $plan['country_id_rec'] = $country['id'];
        $plan['ship_time_early'] = $param['ship_time_early'];
        $plan['ship_time_late'] = $param['ship_time_late'];
        $plan['ctime'] = TIME;
        $plan['user'] = CN_NAME;
        $plan['trading_company'] = $param['trading_company'];//贸易公司
        $plan['retail_company'] = $param['retail_company'];//零售公司
        $plan['overseas_company'] = 10001;//海外公司
        $planDetail = [];
        $pdPush = [];//标记需推送
        $msg = [];
        $sku = array_column($param['list'], 'sku');
        $skuInfo = \app\common\service\SkuService::getBatchInfoBySku($sku, ['ean', 'cnname', 'enname', 'weighting_price']);
        if (empty($skuInfo)) {
            $msg[] = "SKU信息获取失败!";
        }
        //海外公司 YUJISO香港有限公司 10001
        ToolModel::startTrans();
        try {
            if ($param['id']) {
                $id = $param['id'];
                $plan['id'] = $id;
                $isSign = ToolModel::select('ship_plan_detail', ['ship_plan_id' => $param['id'], 'ybr_status' => '1']);
                if (!empty($isSign)) {
                    return returnArr(500, '失败,已经推送给物流,不允许修改!');
                }
                $isSign = ToolModel::select('ship_plan_detail', ['ship_plan_id' => $param['id'], 'bh_status' =>['<>',0]]);
                if (!empty($isSign)) {
                    return returnArr(500, '失败,已经推送给仓库,不允许修改!');
                }
                $planDetailOld = ToolModel::select('ship_plan_detail', ['ship_plan_id' => $param['id']], '*', '', 'id');
                ToolModel::dbInsertOrUpdate('ship_plan', [$plan]);
            } else {
                $id = ToolModel::insertData($plan, 'ship_plan');
                ToolModel::updateData(['id' => $id], ['code' => 'FY' . $id], 'ship_plan');
            }
            if (!$id) {
                ToolModel::rollback();
                return returnArr(500, '生成发运单错误!');
            }
            $getShop = ConfigBase::getShop();
            $shopCountry = ToolModel::select('base_shop', ['status' => 1], 'base_country_id', '', 'id');
            $skuShop = [];
            foreach ($param['list'] as $v) {
                if (empty($v)) {
                    continue;
                }
                $temp = $v;
                $temp['ship_plan_id'] = $id;
                $temp['code'] = 'FY' . $id;
                $temp['ctime'] = TIME;
                if (empty($skuInfo[$v['sku']])) {
                    $msg[] = "sku:{$temp['sku']}在基础资料不存在";
                    continue;
                }
                if (empty($getShop[$v['shop_id']])) {
                    $msg[] = "店铺: {$v['shop_str']}在系统上不存在或被禁用";
                    continue;
                }
                if ($shopCountry[$v['shop_id']] != $country['id']) {
                    $msg[] = "店铺: {$v['shop_str']}对应的国家不是{$country['name_zh']}";
                    continue;
                }
                if (in_array($v['sku'] . $v['shop_id'], $skuShop)) {
                    $msg[] = "sku:{$temp['sku']}存在重复店铺sku";
                    continue;
                }
                if (!empty($v['demand_quantity'])) {
                    if (!preg_match("/^[1-9][0-9]*$/", $v['demand_quantity'])) {
                        $msg[] = "sku:{$temp['sku']}理论需求量必须为正整数";
                        continue;
                    }
                }
                if (!empty($v['real_quantity'])) {
                    if (!preg_match("/^[1-9][0-9]*$/", $v['real_quantity'])) {
                        $msg[] = "sku:{$temp['sku']}实际计划发货量必须为正整数";
                        continue;
                    }
                }
                if (!preg_match("/(^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$)|(^[1-9]\d*$)/", $v['unit_volume'])) {
                    $msg[] = "sku:{$temp['sku']}单位体积{$v['unit_volume']}必须为数字";
                    continue;
                }
                if (!preg_match("/(^[1-9]\d*\.\d*|0\.\d*[1-9]\d*$)|(^[1-9]\d*$)/", $v['unit_price'])) {
                    $msg[] = "sku:{$temp['sku']}单价{$v['unit_price']}必须为数字";
                    continue;
                }
                $temp['sku_name'] = $skuInfo[$temp['sku']]['cnname'] ?? '';
                $temp['sku_enname'] = $skuInfo[$temp['sku']]['enname'] ?? '';
                $temp['ean'] = $skuInfo[$temp['sku']]['ean'] ?? '';
                $temp['unit_price'] = $skuInfo[$temp['sku']]['weighting_price'] ?? 0;
                $temp['total_volume'] = bcmul($temp['real_quantity'], $temp['unit_volume'],9);
                if (!empty($param['id'])) {
                    if (empty($planDetailOld[$v['id']]) || $planDetailOld[$v['id']]['sku'] != $v['sku']) {
                        $msg[] = "sku:{$temp['sku']}在明细中不存在";
                    }
                    $pd = $planDetailOld[$v['id']];
                    if ($pd['ybr_status'] != 1 && $temp['ybr_status'] == 1) {
                            if(config('app_status')!='dev'){
                                if(!in_array($pd['yb_status'],[1,2,3])){
                                $msg[] = "sku:{$temp['sku']}还没有预报结果!";
                                }
                                if($pd['yb_status']==3){
                                    $msg[] = "sku:{$temp['sku']}预报结果为禁运!";
                                }
                            }
                        if (!preg_match("/^[1-9][0-9]*$/", $temp['real_quantity'])) {
                            $msg[] = "sku:{$temp['sku']}标记为配送时实际计划发货量必须为正整数!";
                        }
                        $pdPush[] = $temp;
                    }
                    if ($pd['ybr_status'] == 1) {
                        if ($v['demand_quantity'] != $pd['demand_quantity']) {
                            $msg[] = "sku:{$temp['sku']}已推送不允许修改";
                        }
                        if ($v['real_quantity'] != $pd['real_quantity']) {
                            $msg[] = "sku:{$temp['sku']}已推送不允许修改";
                        }
                        continue;
                    }
                }
                $skuShop[] = $v['sku'] . $v['shop_id'];
                unset($temp['LAY_TABLE_INDEX']);
                unset($temp['shop_str']);
                unset($temp['yb_opinion']);
                unset($temp['newAdd']);
                unset($temp['yb_status']);
                unset($temp['bh_status']);
                unset($temp['delivery_quantity']);
                unset($temp['bh_str_status']);
                unset($temp['yb_str_status']);
                unset($temp['ybr_str_status']);
                $planDetail[] = $temp;
            }
            if (!empty($msg)) {
                ToolModel::rollback();
                return returnArr(500, $msg);
            }
            ToolModel::dbInsertOrUpdate('ship_plan_detail', $planDetail);
            if (!empty($param['id'])) {
                if (!empty($pdPush)) {
                    //推送给仓库
                    $pushRes=ShipService::pushShipInfoByWms($id);
                    if ($pushRes['code'] != 1) {
                        $msg[]='全部失败,推送仓库失败导致修改失败标记失败!原因'.$pushRes['msg'];
                        if (!empty($msg)) {
                            ToolModel::rollback();
                            return returnArr(500, $msg);
                        }
                    }
                    ToolModel::updateData(['ship_plan_id'=>$id,'ybr_status'=>1],['bh_status'=>1],'ship_plan_detail');
                    ToolModel::updateData(['id'=>$id],['bh_status'=>1],'ship_plan');
                    //存在标记配送时 第二次推送头程
                    $pushRes = self::pushShipInfo($id, config("wuliu") . 'public/index.php?s=thirdparty/Test/getShipPlanOrderInfo', ['push_logo' => 2]);
                    if ($pushRes['code'] == 1) {
                        ToolModel::updateData(['id'=>$id],['tc_status'=>20],'ship_plan');
                    } else {
                        $msg[]='全部失败,请联系管理员推送仓库成功 推送头程失败 !原因'.$pushRes['msg'];
                        if (!empty($msg)) {
                            ToolModel::rollback();
                            trace("发运id:{$id}推送仓库成功,推送头程失败!",'error');
                            return returnArr(500, $msg);
                        }
                    }
                }
                self::updateYbrStatus($param['id']);
            } else {
                //第一次创建时推送头程
                $res = self::pushShipInfo($id, config("wuliu") . 'public/index.php?s=thirdparty/Test/getShipPlanOrderInfo', ['push_logo' => 1]);
                if ($res['code'] == 1) {
                    ToolModel::updateData(['ship_plan_id' => $id], ['yb_status' => 10], 'ship_plan_detail');
                    ToolModel::updateData(['id' => $id], ['yb_status' => 10], 'ship_plan');
                } else {
                    $msg[] = "推送头程系统失败!".$res['msg'];
                }
            }
            if (!empty($msg)) {
                ToolModel::rollback();
                return returnArr(500, $msg);
            }
            ToolModel::commit();
            if ($param['id']) {
                if (!empty($pdPush)) {
                    return returnArr(1, '成功', ['url' => '#/Ship/index']);
                }else{
                    return returnArr(1, '成功');
                }
            } else {
                return returnArr(1, '成功', ['url' => '#/Ship/index']);
            }
        } catch (\Exception $e) {
            ToolModel::rollback();
            trace($e->getMessage(), 'error');
            return returnArr(600, '失败' . $e->getMessage());
        }
    }

    //修改总预报结果
    static public function updateYbrStatus($id)
    {
        $planDetail = ToolModel::select('ship_plan_detail', ['ship_plan_id' => $id, 'ybr_status' => 1]);
        if (!empty($planDetail)) {
            ToolModel::updateData(['id' => $id], ['ybr_status' => 1], 'ship_plan');
        }
    }

    //推送仓库和物流
    static public function push($pdPush)
    {
        if (!empty($pdPush)) {
            return returnArr(1);
        } else {
            return returnArr(1);
        }
    }

    static public function detail($param)
    {
        $plan[] = [];
        $detail = [];
        if (!empty($param['id'])) {
            $plan = ToolModel::select('ship_plan', ['id' => $param['id']]);
            $detail = ToolModel::select('ship_plan_detail', ['ship_plan_id' => $param['id']]);
            $detail = self::detailHandle($detail, $plan[0]['code']);
            $plan = self::getListHandle($plan);
        }
        $countryWarehouse = ToolModel::select('base_warehouse', ['type' => ['in', [2]]], 'warehouse_name', '', 'id');
        $myCompany = ToolModel::select('base_company', ['type' => ['in', [1, 3]]], 'company_name', '', 'id');
        $lsCompany = ToolModel::select('base_company', ['type' => ['in', [2]]], 'company_name', '', 'id');
        return returnArr(1, '', ['plan' => $plan[0], 'detail' => $detail, 'lsCompany' => $lsCompany, 'myCompany' => $myCompany, 'countryWarehouse' => $countryWarehouse]);
    }

    static public function detailHandle($detail, $code)
    {
        $getShop = ConfigBase::getShopAll();
        $send = ToolModel::select('ship_plan_send', ['code' => $code]);
        $yb = ToolModel::select('ship_plan_prognosis', ['code' => $code]);
        $sendPd = [];
        foreach ($send as $v2) {
            if(empty($sendPd[$v2['shop_id'] . $v2['sku']])){
                $sendPd[$v2['shop_id'] . $v2['sku']] = $v2['quantity'];
            }else{
                $sendPd[$v2['shop_id'] . $v2['sku']] += $v2['quantity'];
            }
        }
        unset($send);
        $ybPd = [];
        foreach ($yb as $v3) {
            $ybPd[$v3['sku']] = $v3['opinion'];
        }
        unset($yb);
        foreach ($detail as &$v) {
            if (!empty($sendPd[$v['shop_id'] . $v['sku']])) {
                $v['delivery_quantity'] = $sendPd[$v['shop_id'] . $v['sku']];
            } else {
                $v['delivery_quantity'] = 0;
            }
            if (!empty($ybPd[$v['sku']])) {
                $v['yb_opinion'] = $ybPd[$v['sku']];
            }
            $v['shop_str'] = $getShop[$v['shop_id']];
            $v['yb_str_status'] = self::$ybStatus[$v['yb_status']];
            $v['bh_str_status'] = self::$bhStatus[$v['bh_status']]??'';
            $v['ybr_str_status'] = self::$ybrStatus[$v['ybr_status']];
        }
        return $detail;
    }

    static public function getList($param)
    {
        if (empty($param['down'])) {
            $titles = [];
        } else {
            $titles = [
                'code' => '发运计划单号',
                'sku_num' => 'SKU',
                'company_str_out' => '发货公司',
                'warehouse_str_out' => '发货仓库',
                //'shop_str_rec'=>'收货店铺',
                'warehouse_str_rec' => '收货仓',
                'country_str_rec' => '收货国家',
                'ship_time_early' => '最早发运时间',
                'ship_time_late' => '最晚发运时间',
                'yb_str_status' => '预报状态',
                'bh_str_status' => '仓库状态',
                'tc_str_status' => '头程状态',
                'ctime' => '创建时间',
            ];
        }
        return ShipModel::getList($param, $titles, "\app\index\service\ShipService::getListHandle");
    }

    static public function logistics($param)
    {
        if (empty($param['down'])) {
            $titles = [];
        } else {
            $titles = [
                'local_order_no' => '物流内单号',
                'box_number' => '箱唛号',
                'booking_space_date' => '订舱日期',
                'Shipment_date' => '仓库出货日期',
                'receiving_goods_date' => '货代收货日期',
                'out_customs_clearance_date' => '出口清关日期',
                'reality_departure_date' => '实际离港日期',
                'reality_arrival_date' => '实际抵港日期',
                'in_customs_clearance_date' => '进口清关日期',
                'reality_send_date' => '实际派送日期',
                'goods_online_date' => '货物上架日期',
                'quantity' => '签收数量'
            ];
        }
        return ShipModel::logistics($param, $titles,"\app\index\service\ShipService::logisticsHandle");
    }
    static public function logisticsHandle($data){
        foreach ($data as &$v){
           foreach ($v as &$v2){
               if($v2=='0000-00-00 00:00:00'){
                   $v2='';
               }
           }
        }
        return $data;
    }
    static public function getListHandle($data)
    {
        $country = ConfigBase::getCountry();
        //$shop=ConfigBase::getShopAll();
        $company = ConfigBase::getCompanyAll();
        $warehouse = ConfigBase::getWarehouseAll();
        $skuNum = ShipModel::getSKuNum(array_column($data, 'id'));
        foreach ($data as &$v) {
            $v['company_str_out'] = $company[$v['company_id_out']];
            $v['warehouse_str_out'] = $warehouse[$v['warehouse_id_out']];
            //$v['shop_str_rec']=$shop[$v['shop_id_rec']];
            $v['warehouse_str_rec'] = $warehouse[$v['warehouse_id_rec']] ?? '';
            $v['country_str_rec'] = $country[$v['country_id_rec']];
            $v['yb_str_status'] = self::$ybStatus[$v['yb_status']];
            $v['bh_str_status'] = self::$bhStatus[$v['bh_status']]??'';
            $v['tc_str_status'] = self::$tcStatus[$v['tc_status']];
            $v['sku_num'] = $skuNum[$v['id']];
            $v['retail_str_company'] = $company[$v['retail_company']] ?? '';
            $v['company_str_overseas'] = $company[$v['overseas_company']] ?? '';
            $v['trading_str_company'] = $company[$v['trading_company']] ?? '';
        }
        return $data;
    }

    static public function getCompanyType($param)
    {
        $my = ToolModel::findByAttributes('base_company', ['base_country_name' => $param['name'], 'type' => ['in', [1, 3]]]);
        $ls = ToolModel::findByAttributes('base_company', ['base_country_name' => $param['name'], 'type' => ['in', [2, 3]]]);
        return returnArr(1, '', ['my' => $my, 'ls' => $ls]);
    }

    //推送给头程发运计划
    static public function pushShipInfo($id, $url, $param)
    {
        if(config('app_status')=='dev'){
            return returnArr(1);
        }
        $plan = ToolModel::findByAttributes('ship_plan', ['id' => $id]);
        $countryCode = ToolModel::getValue('base_country',['id'=>$plan['country_id_rec']],'country_code');
        $shipment_company = ConfigBase::getCompanyAll(['id' => $plan['company_id_out']]);
        $shipment_warehouse = ConfigBase::getWarehouseAll(['id' => $plan['warehouse_id_out']]);
        $destinationWarehouse=ToolModel::findByAttributes('base_warehouse',['id'=> $plan['warehouse_id_rec']]);
        $data = [];
        $data['order_no'] = $plan['code'];
        $data['push_logo'] = $param['push_logo'];
        $data['shipment_company'] = $shipment_company[$plan['company_id_out']];
        $data['shipment_warehouse'] = $shipment_warehouse[$plan['warehouse_id_out']];
        $data['destination_warehouse'] = $destinationWarehouse['warehouse_name'];
        $data['destination_warehouse_address'] = $destinationWarehouse['address'];
        $data['destination_country'] =$countryCode;
        $data['start_shipment_date'] = $plan['ship_time_early'];
        $data['end_shipment_date'] = $plan['ship_time_late'];
        $temp = [];
        if($data['push_logo']==2){
            $planDetail = ToolModel::select('ship_plan_detail', ['ship_plan_id' => $id,'ybr_status'=>1]);
        }else{
            $planDetail = ToolModel::select('ship_plan_detail', ['ship_plan_id' => $id]);
        }
        foreach ($planDetail as $v) {
            $temp[$v['sku']]['sku'] = $v['sku'];
            $temp[$v['sku']]['theory_qty'] = !empty($temp[$v['sku']]['theory_qty']) ? ($temp[$v['sku']]['theory_qty'] + $v['demand_quantity']) : $v['demand_quantity'];
            $temp[$v['sku']]['reality_qty'] = !empty($temp[$v['sku']]['reality_qty']) ? ($temp[$v['sku']]['reality_qty'] + $v['real_quantity']) : $v['real_quantity'];
            $temp[$v['sku']]['price'] = $v['unit_price'];
        }
        $data['sku_info'] = array_values($temp);
        $ret = curl($url, ['data' => [$data]]);
        $res = json_decode($ret, true);
        if (is_array($res) && $res['state'] == '000001') {
            if (!empty($res['order_no']['success']) && $res['order_no']['success'][0] == $plan['code']) {
                return returnArr(1);
            }
        }
        trace("{$url}: " . json_encode($data) . $ret, 'error');
        $msg='';
        if(!empty($res['order_no']['fail'])&&!empty($res['order_no']['fail'][$plan['code']])){
            $msg=$res['order_no']['fail'][$plan['code']];
        }
        return returnArr(500, '推送计划给头程系统调用失败'.$msg);
    }
    //推送给仓库发运计划
    static public function pushShipInfoByWms($id)
    {
        if(config('app_status')=='dev'){
            return returnArr(1);
        }
        $url = config("wms") . "index.php/api/Pick/createPick";
        $plan = ToolModel::findByAttributes('ship_plan', ['id' => $id]);
        $planDetail=Db::table('ship_plan_detail')
            ->alias('a')
            ->field('a.*,b.shop_name')
            ->join('base_shop b','a.shop_id=b.id')
            ->where(['ship_plan_id' => $id])
            ->where('ybr_status',1)
            ->select();
        $countryCode = ToolModel::getValue('base_country',['id'=>$plan['country_id_rec']],'country_code');
        $data = [];
        $data['ship_number'] = $plan['code'];
        $data['receive_country'] =$countryCode;
        $data['latest_ship_time'] = $plan['ship_time_late'];
        $data['create_by'] =$plan['user'];
        $temp = [];
        foreach ($planDetail as $v) {
            $temp['sku_code'] = $v['sku'];
            $temp['cn_name'] = $v['sku_name'];
            $temp['en_name'] = $v['sku_enname'];
            $temp['plan_sku_qty'] =$v['real_quantity'];
            $temp['price'] = $v['unit_price'];
            $temp['receive_warehouse']=$v['shop_name'];
            $temp['ean_code']=$v['ean'];
            $data['sku_info'][]=$temp;
        }
        $ret = curl($url, $data,array('Content-Type: application/json','appkey: 6hVxcxnXfSutI57Q',"apptoken: Q1EVxkMT0Km8c7JoOVu6LQgVK2qNMHbN"));
        $msg=[];
        $res = json_decode($ret, true);
        $ok=0;
        if (is_array($res) && $res['state'] == '200') {

        }else{
            if (is_array($res) && $res['state'] != '200') {
                foreach ($res['msg'] as $v2){
                    if(isset($v2['result']['is_success'])&&$v2['result']['is_success']!=1){
                        $msg[]=$v2['result']['sku_type']??($v2['result']['sku_code']??($v2['result']['plan_sku_qty']??''));
                    }
                }
            }
            $ok=1;
        }
        if($ok==1){
            return returnArr(500, '推送推送给仓库发运计划调用失败'.join(',',$msg));
        }
        return returnArr(1);
    }
    //推送给仓库取消发运计划
    static public function pushCancelShipWms($param)
    {
        $url = config("wms") . "index.php/api/Pick/cancelPick";
        $planDetail=Db::table('ship_plan_detail')
            ->alias('a')
            ->field('a.*,b.shop_name')
            ->join('base_shop b','a.shop_id=b.id')
            ->where(['ship_plan_id' =>$param['id'],'sku'=>$param['sku']])
            ->find();
        $ret = curl($url,[
            'ship_number'=>$planDetail['code']
            ,'sku_code'=>$planDetail['sku']
            ,'receive_warehouse'=>$planDetail['shop_name']
        ],array('Content-Type: application/json','appkey: 6hVxcxnXfSutI57Q',"apptoken: Q1EVxkMT0Km8c7JoOVu6LQgVK2qNMHbN"));
        $res = json_decode($ret, true);
        if (is_array($res) && $res['state'] == '200') {
            return returnArr(1);
        }else{
            return returnArr(500, '返回失败原因:'.$res['msg']??'');
        }
    }
    //装箱单列表接口
    static public function getPlanSendByWms()
    {
        $time = ConfigBase::getTasksTime(40);
        $url = config("wms") . "index.php/api/Box/boxList";
        $data = ['startTime' => $time,'endTime'=>date("Y-m-d H:i:s")];
        $ret = curl($url, $data,array('Content-Type: application/json','appkey: 6hVxcxnXfSutI57Q',"apptoken: Q1EVxkMT0Km8c7JoOVu6LQgVK2qNMHbN"));
        $res = json_decode($ret, true);
        $shop=ToolModel::select('base_shop',[],'id','','shop_name');
        $code=[];
        if (is_array($res) && $res['state'] == '200') {
            if (!empty($res['data'])) {
                $list = [];
                foreach ($res['data'] as $k=>$v) {
                    foreach ($v['box_order'] as $k2=>$v2){
                        if(empty($shop[$v['receive_warehouse']])&&config('app_status')=='pro'){
                            trace($v['receive_warehouse']."获取装箱单列表接口失败,店铺id为空".json_encode($v), 'error');
                            return returnArr(500,'获取装箱单列表接口失败,店铺id为空');
                        }
                        ToolModel::updateData(['code' => $v['ship_number'], 'sku' =>$v['sku_code'],'shop_id'=> $shop[$v['receive_warehouse']]??0], ['bh_status' => $v['pick_status']], 'ship_plan_detail');
                        $list[] = [
                            'code' => $v['ship_number'],
                            'box_number' => $v2,
                            'sku' => $v['sku_code'],
                            'shop_id' => $shop[$v['receive_warehouse']]??0,
                            'quantity' => $v['per_box_qty'],
                            'date' => $v['create_time'],
                            'ctime' => TIME
                        ];
                        $code[$v['ship_number']]=1;
                    }
                }
                if(empty($list)){
                    return returnArr(500);
                }
                $plan=DB::table('ship_plan_detail')
                    ->field('min(bh_status) as bh_status,code')
                    ->where('code','in',array_keys($code))
                    ->group('code')
                    ->select();
                foreach ($plan as $v3){
                    ToolModel::updateData(['code' => $v3['code']], ['bh_status' => $v3['bh_status']], 'ship_plan');
                }
                ToolModel::dbInsertOrUpdate('ship_plan_send', $list);
                ConfigBase::insertTasksTime(40);
                return returnArr(1);
            }
        } else {
            //trace("{$url}: " . json_encode($data) . $ret, 'error');
            return returnArr(500, '获取装箱单列表接口失败'.$res['msg']);
        }
    }


    //获取头程预报结果意见
    static public function getPrognosis()
    {
        $time = ConfigBase::getTasksTime(10);
        $url = config("wuliu") . "public/index.php?s=thirdparty/Test/getSkuForecastResultInfo";
        $data = ['update_at' => $time];
        $ret = curl($url, $data);
        $res = json_decode($ret, true);
        if (is_array($res) && $res['state'] == '000001') {
            if (!empty($res['data'])) {
                $list = [];
                $code = [];
                foreach ($res['data'] as $k=>$v) {
                    foreach ($v as $k2=>$v2){
                        if(empty($v2['logistics_id'])){
                            continue;
                        }
                        $list[] = [
                            'code' =>$k,
                            'sku' => $k2,
                            'ctime' => TIME,
                            'status' => $v2['logistics_id'],
                            'opinion' => $v2['logistics_opinion']
                        ];
                        ToolModel::updateData(['code' => $k, 'sku' => $k2], ['yb_status' => $v2['logistics_id']], 'ship_plan_detail');
                    }
                    $code[$k] = 1;
                }
                ToolModel::dbInsertOrUpdate('ship_plan_prognosis', $list);
                $temp = ToolModel::select('ship_plan_detail', ['code' => ['in', array_keys($code)]], 'yb_status,code,sku');
                $tempYb = [];
                foreach ($temp as $v2) {
                    if ($v2['yb_status'] == 1) {
                        $tempYb[$v2['code']][1] = isset($tempYb[$v2['code']]) && !empty($tempYb[$v2['code']][1]) ? ($tempYb[$v2['code']][1] + 1) : 1;
                    } elseif ($v2['yb_status'] == 2) {
                        $tempYb[$v2['code']][2] = isset($tempYb[$v2['code']]) && !empty($tempYb[$v2['code']][2]) ? ($tempYb[$v2['code']][2] + 1) : 1;
                    } elseif ($v2['yb_status'] == 3) {
                        $tempYb[$v2['code']][3] = isset($tempYb[$v2['code']]) && !empty($tempYb[$v2['code']][3]) ? ($tempYb[$v2['code']][3] + 1) : 1;
                    }
                    $tempYb[$v2['code']][4] = isset($tempYb[$v2['code']]) && !empty($tempYb[$v2['code']][4]) ? ($tempYb[$v2['code']][4] + 1) : 1;
                }
                foreach ($tempYb as $k3 => $v3) {
                    $yb = 0;
                    if (isset($v3[1])&&$v3[4] == $v3[1]) {
                        $yb = 1;
                    } elseif (isset($v3[3])&&$v3[4] == $v3[3]) {
                        $yb = 3;
                    } elseif (isset($v3[2])&&$v3[2] > 0) {
                        $yb = 2;
                    }
                    !empty($yb)&&ToolModel::updateData(['code' => $k3], ['yb_status' => $yb], 'ship_plan');
                }
                ConfigBase::insertTasksTime(10);
                return returnArr(1,'成功');
            }
        } else {
            trace("{$url}: " . json_encode($data) . $ret, 'error');
            return returnArr(500, '获取头程预报结果意见失败');
        }
    }

    //获取头程签收箱和SKU信息
    static public function getReceive()
    {
        $time = ConfigBase::getTasksTime(20);
        $data = ['update_at' => $time];
        $url = config("wuliu") . "public/index.php?s=thirdparty/Test/getSignAndSkuInfo";
        $ret = curl($url, $data);
        $res = json_decode($ret, true);
        if (is_array($res) && $res['state'] == '000001') {
            if (!empty($res['data'])) {
                $list = [];
                $code = [];
                foreach ($res['data'] as $v) {
                    foreach ($v as $v2){
                        $list[] = [
                            'code' => $v2['order_no'],
                            'sku' => $v2['sku'],
                            'case_number' => $v2['box_number'],
                            'quantity' => $v2['qty'],
                            'ctime' => TIME
                        ];
                        $code[$v2['order_no']] = 1;
                    }
                }
                $orderNo = array_keys($code);
                $shopId=ToolModel::select('ship_plan_send',['code'=>['in',$orderNo]],'shop_id','','box_number');
                $ok = 1;
                foreach ($list as &$v3){
                    $v3['shop_id']=$shopId[$v3['case_number']]??0;
                    if(empty($v3['shop_id'])&&config('app_status')=='pro'){
                        trace('ship_plan_send对应的箱唛号找不到'.json_encode($v3), 'error');
                        $ok = 0;
                    }
                }
                ToolModel::dbInsertOrUpdate('ship_plan_receive', $list);
                if ($ok == 0) {
                    return returnArr(500, '失败');
                }
                foreach ($orderNo as $v2) {
                    $createRet = PurchasemanageService::createAuto(['code' => $v2]);
                    if ($createRet['code'] != 1 && $createRet['code'] != 2) {
                        if(config('app_status')=='pro'){
                            trace($createRet['msg'] . '根据头程签收数量生成采购入库失败' . $v2, 'error');
                            $ok = 0;
                        }
                    }
                }
                if ($ok == 1) {
                    ConfigBase::insertTasksTime(20);
                    return returnArr(1);
                } else {
                    return returnArr(500, '失败');
                }
            }
        } else {
            trace("{$url}: " . json_encode($data) . $ret, 'error');
            return returnArr(500, '获取头程签收箱和SKU信息失败');
        }
    }

    //获取头尾程费用信息
    static public function getPlanCost()
    {
        $time = ConfigBase::getTasksTime(30);
        $url = config("wuliu") . "public/index.php?s=thirdparty/Test/getShipCostInfo";
        $data = ['update_at' => $time];
        $ret = curl($url, $data);
        $res = json_decode($ret, true);
        if (is_array($res) && $res['state'] == '000001') {
            if (!empty($res['data'])) {
                $list = [];
                foreach ($res['data'] as $k=>$v) {
                    foreach ($v as $k2=>$v2){
                        if($k2=='order_no'){
                            continue;
                        }
                        if(empty($k2)){
                            continue;
                        }
                        $list[] = [
                            'code' => $k,
                            'sku' => $k2,
                            'head' => $v2['head_charges'],
                            'end' => $v2['tail_charges'],
                            'ctime' => TIME
                        ];
                    }
                }
                ToolModel::dbInsertOrUpdate('ship_plan_cost', $list);
                ConfigBase::insertTasksTime(30);
                return returnArr(1);
            }
        } else {
            trace("{$url}: " . json_encode($data) . $ret, 'error');
            return returnArr(500, '获取头尾程费用信息失败');
        }
    }

    //获取头程物流信息
    static public function getLogistics()
    {
        $time = ConfigBase::getTasksTime(50);
        $url = config("wuliu") . "public/index.php?s=thirdparty/Test/getShipDateInfo";
        $data = ['update_at' => $time];
        $ret = curl($url, $data);
        $res = json_decode($ret, true);
        if (is_array($res) && $res['state'] == '000001') {
            if (!empty($res['data'])) {
                $list = [];
                $code = [];
                foreach ($res['data'] as $v) {
                    foreach ($v['box_number'] as $v2){
                        $temp=[];
                        $temp['local_order_no']=$v['local_order_no'];
                        $temp['booking_space_date']=$v['booking_space_date'];
                        $temp['Shipment_date']=$v['Shipment_date'];
                        $temp['receiving_goods_date']=$v['receiving_goods_date'];
                        $temp['out_customs_clearance_date']=$v['out_customs_clearance_date'];
                        $temp['reality_departure_date']=$v['reality_departure_date'];
                        $temp['reality_arrival_date']=$v['reality_arrival_date'];
                        $temp['in_customs_clearance_date']=$v['in_customs_clearance_date'];
                        $temp['reality_send_date']=$v['reality_send_date'];
                        $temp['goods_online_date']=$v['goods_online_date'];
                        $temp['code'] = $v['order_no'];
                        $temp['ctime'] = TIME;
                        $temp['box_number']=$v2;
                        $list[] = $temp;
                        $code[$v['order_no']] = $temp;
                    }
                }
                ToolModel::dbInsertOrUpdate('ship_plan_logistics', $list);
                foreach ($code as $v2) {
                    $tc = 0;
                    if (!empty($v['goods_online_date'])&&$v['goods_online_date']!='0000-00-00 00:00:00') {
                        $tc = 9;
                    } elseif (!empty($v['reality_send_date'])&&$v['reality_send_date']!='0000-00-00 00:00:00') {
                        $tc = 8;
                    } elseif (!empty($v['in_customs_clearance_date'])&&$v['in_customs_clearance_date']!='0000-00-00 00:00:00') {
                        $tc = 7;
                    } elseif (!empty($v['reality_arrival_date'])&&$v['reality_arrival_date']!='0000-00-00 00:00:00') {
                        $tc = 6;
                    } elseif (!empty($v['reality_departure_date'])&&$v['reality_departure_date']!='0000-00-00 00:00:00') {
                        $tc = 5;
                    } elseif (!empty($v['out_customs_clearance_date'])&&$v['out_customs_clearance_date']!='0000-00-00 00:00:00') {
                        $tc = 4;
                    } elseif (!empty($v['receiving_goods_date'])&&$v['receiving_goods_date']!='0000-00-00 00:00:00') {
                        $tc = 3;
                    } elseif (!empty($v['Shipment_date'])&&$v['Shipment_date']!='0000-00-00 00:00:00') {
                        $tc = 2;
                    } elseif (!empty($v['booking_space_date'])&&$v['booking_space_date']!='0000-00-00 00:00:00') {
                        $tc = 1;
                    }
                    ToolModel::updateData(['code' => $v2['code']], ['tc_status' => $tc], 'ship_plan');
                }
                ConfigBase::insertTasksTime(50);
                return returnArr(1);
            }
        } else {
            trace("{$url}: " . json_encode($data) . $ret, 'error');
            return returnArr(500, '获取头程物流信息失败');
        }
    }
}